﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Services.Client;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Input;
using System.Xml.Linq;
using DevComponents.WPF.Controls; 
using Microsoft.Practices.Prism.Commands;
using ZhiHeng.Consume.DataContract;
using ZhiHeng.OneCard.CommUtility;
using ZhiHeng.OneCard.WpfClient.Common;
using ZhiHeng.OneCard.WpfClient.Model;

using Menu = ZhiHeng.OneCard.WpfClient.Model.Menu;
using MessageBox = System.Windows.MessageBox;

namespace ZhiHeng.OneCard.WpfClient.ViewModel
{
    internal class OperatorRightViewModel : ViewModelBase
    {
        public OperatorRightViewModel()
        {
            //隐藏编辑组界面
            IsShow = Visibility.Hidden;
            LoadData();

            if (_tempop == null)
                _tempop = new @operator();
            _tempop.Used = 1;
            _tempop.USERIP = GetLocalIP();
        }
        #region 绑定所需属性
        private static ObservableCollection<TreeViewEntity> _nodes;
        /// <summary>
        /// 程序配置文件
        /// </summary>
        public static ObservableCollection<TreeViewEntity> Nodes
        {
            get
            {
                if (_nodes == null)
                {
                    string xpath = "Config/Menu.xml";
                    XElement root = XElement.Load(xpath);
                    Nodes = GetMenus(root);
                }
                return _nodes;
            }
            set
            {
                _nodes = value;

            }
        }


        private operatorGroup _tempopgroup;
        /// <summary>
        /// 界面绑定需要的角色组信息
        /// </summary>
        public operatorGroup TempOpGroup
        {
            get
            {
                if (_tempopgroup == null)
                    _tempopgroup = new operatorGroup();
                return _tempopgroup;
            }
            set
            {
                _tempopgroup = value;
                RaisePropertyChanged("TempOpGroup");
            }
        }


        private operatorGroup _tempSelectGrop;
        /// <summary>
        /// 界面绑定需要的角色组信息
        /// </summary>
        public operatorGroup TempSelectGrop
        {
            get
            {
                if (_tempSelectGrop == null)
                    _tempSelectGrop = new operatorGroup();
                return _tempSelectGrop;
            }
            set
            {
                _tempSelectGrop = value;
                RaisePropertyChanged("TempSelectGrop");
            }
        }



        private operatorGroup _selectedopgroup;
        /// <summary>
        /// 选中的角色组信息
        /// </summary>
        public operatorGroup SelecetedOpGroup
        {
            get
            {
                if (_selectedopgroup == null)
                {
                    _selectedopgroup = new operatorGroup();
                }
                return _selectedopgroup;
            }
            set
            {
                _selectedopgroup = value;

                //TempOpGroup.Name = SelecetedOpGroup.Name;
                //TempOpGroup.Flag = SelecetedOpGroup.Flag;
                //TempOpGroup.OPERDESC = SelecetedOpGroup.OPERDESC;
                TempOpGroup = SelecetedOpGroup.Clone();
                if (TempOpGroup.Flag != null)
                {
                    var a = TreeInfo.Where(p => p.Code == int.Parse(TempOpGroup.Flag));
                    if (a.Any()) //获取程序权限
                    {
                        SeletedTreeInfo = a.First();

                        foreach (TreeViewEntity temp in Nodes)
                        {
                            if (!string.IsNullOrEmpty(_selectedopgroup.OperLevel) &&
                                _selectedopgroup.OperLevel.IndexOf((temp.Data as Menu).Id) > -1)
                            {
                                temp.IsChecked = true;
                            }
                            else
                            {
                                temp.IsChecked = false;
                            }

                            foreach (TreeViewEntity tempson in temp.DataSon)
                            {
                                if (!string.IsNullOrEmpty(_selectedopgroup.OperLevel) &&
                                    _selectedopgroup.OperLevel.IndexOf((tempson.Data as Menu).Id) > -1)
                                {
                                    tempson.IsChecked = true;
                                }
                                else
                                {
                                    tempson.IsChecked = false;
                                }

                            }
                        }
                    }
                }
                RaisePropertyChanged("SelecetedOpGroup");
            }
        }





        private ObservableCollection<operatorGroup> _opgroup = new ObservableCollection<operatorGroup>();
        /// <summary>
        /// 角色组表数据
        /// </summary>
        public ObservableCollection<operatorGroup> OpGroup
        {
            get
            {
                return _opgroup;
            }
            set
            {
                _opgroup = value;
                RaisePropertyChanged("OpGroup");
            }
        }

        private @operator _selectedop;
        /// <summary>
        /// 选中的操作员信息
        /// </summary>
        public @operator SelecetedOp
        {
            get { return _selectedop; }
            set
            {
                _selectedop = value;
                if (_selectedop==null)
                {
                    return;
                }
                TempOP = _selectedop.Clone();
                RaisePropertyChanged("SelecetedOp");
                if (string.IsNullOrEmpty(TempOP.Flag))
                {
                    IsCash = false;
                }
                else
                {
                    IsCash = TempOP.Flag.Trim() == "1";
                }

            }
        }

        private @operator _tempop;
        /// <summary>
        /// 界面绑定需要的信息
        /// </summary>
        public @operator TempOP
        {
            get
            {

                return _tempop;
            }
            set
            {
                _tempop = value;
                RaisePropertyChanged("TempOP");
            }
        }



        private @operator _queryop;
        /// <summary>
        /// 查询条件需要的绑定信息
        /// </summary>
        public @operator QueryOP
        {
            get
            {
                if (_queryop == null)
                {
                    //赋默认值
                    _queryop = new @operator();
                    _queryop.GroupCode = -1;
                    _queryop.Used = -1;
                }
                return _queryop;
            }
            set
            {
                _queryop = value;
                RaisePropertyChanged("QueryOP");
            }

        }

        private ObservableCollection<@operator> _op;
        /// <summary>
        /// 操作员表信息
        /// </summary>
        public ObservableCollection<@operator> OP
        {
            get
            {
                return _op;
            }
            set
            {
                _op = value;
                RaisePropertyChanged("OP");
            }
        }

        private ConfigTreeInfo _seletedTreeInfo;
        /// <summary>
        /// 下拉列表需要的字典信息
        /// </summary>
        public ConfigTreeInfo SeletedTreeInfo
        {
            get
            {
                return _seletedTreeInfo;
            }
            set
            {
                _seletedTreeInfo = value;
                RaisePropertyChanged("SeletedTreeInfo");
            }
        }

        private bool _iscash = true;

        public bool IsCash
        {
            get
            {
                return _iscash;
            }
            set
            {
                _iscash = value;
                RaisePropertyChanged("IsCash");
            }
        }


        /// <summary>
        /// 商户表数据
        /// </summary>

        ObservableCollection<mercacc> _Mercaccs = new ObservableCollection<mercacc>();
        public ObservableCollection<mercacc> Mercaccs
        {
            get
            {
                return _Mercaccs;
            }
            set
            {
                _Mercaccs = value;
                RaisePropertyChanged("Mercaccs");
            }
        }



        ObservableCollection<mercacc> _MercaccsPlus = new ObservableCollection<mercacc>();
        public ObservableCollection<mercacc> MercaccsPlus
        {
            get
            {
                return _MercaccsPlus;
            }
            set
            {
                _MercaccsPlus = value;

            }
        }

        private int _selectMercaccsPlus;

        public int SelectMercaccsPlus
        {
            get { return _selectMercaccsPlus; }
            set
            {
                _selectMercaccsPlus = value;
                RaisePropertyChanged("SelectMercaccsPlus");
            }
        }



        ObservableCollection<operatorGroup> _GropPlus = new ObservableCollection<operatorGroup>();
        public ObservableCollection<operatorGroup> GropPlus
        {
            get
            {
                return _GropPlus;
            }
            set
            {
                _GropPlus = value;

            }
        }

        private int _selectGropPlus;

        public int SelectGropPlus
        {
            get { return _selectGropPlus; }
            set
            {
                _selectGropPlus = value;
                RaisePropertyChanged("SelectGropPlus");
            }
        }

        /// <summary>
        /// 字典数据
        /// </summary>
        public IEnumerable<ConfigTreeInfo> TreeInfo { get; set; }

        private Visibility _isshow;
        /// <summary>
        /// 是否显示编辑角色组
        /// </summary>
        public Visibility IsShow
        {
            get { return _isshow; }
            set
            {
                _isshow = value;
                RaisePropertyChanged("IsShow");
            }
        }

        #endregion

        #region 方法


        void LoadData()
        {
            GropPlus.Clear();
            _MercaccsPlus.Clear(); 
            //启动时需要加载的数据
            TreeInfo = StaticDicdictionary.TreeDicdictionary.Where(p => p.Type == 4);
            OpGroup = new ObservableCollection<operatorGroup>(new operatorGroup().ExtGetAll());
            if (OpGroup.Count > 0)
            {
                //TempOP.GroupCode = OpGroup.First().Id;
                operatorGroup tempop = new operatorGroup { Id = -1, Name = "全部" };
                GropPlus.Add(tempop);
                foreach (operatorGroup ogp in OpGroup)
                {
                    GropPlus.Add(ogp);
                }
            }

            mercacc temp = new mercacc
            {
                Account = -1,
                MercName = "全部"
            };
            _MercaccsPlus.Add(temp);
            Mercaccs = new ObservableCollection<mercacc>(new mercacc().ExtGetAll());
            foreach (mercacc m in Mercaccs)
            {
                MercaccsPlus.Add(m);
            }

            SelectGropPlus = -1;
            SelectMercaccsPlus = -1;
        }

        /// <summary>
        /// 配置文件xml转泛型
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        private static ObservableCollection<TreeViewEntity> GetMenus(XElement root)
        {
            var list = new ObservableCollection<TreeViewEntity>();
            foreach (var xElement in root.Elements("Menu"))
            {
                var newMenu = new Model.Menu();

                newMenu.Id = xElement.AttributeValue("id");
                newMenu.Name = xElement.AttributeValue("name");
                newMenu.Order = int.Parse(xElement.AttributeValue("order"));
                string color = xElement.AttributeValue("tileColor");
                newMenu.TileColor = color;
                newMenu.Icon = xElement.AttributeValue("icon");
                newMenu.Form = xElement.AttributeValue("form");
                newMenu.Width = xElement.AttributeValue("Width");
                newMenu.Height = xElement.AttributeValue("Height");
                newMenu.BgColor1 = xElement.AttributeValue("bgColor1");
                newMenu.BgColor2 = xElement.AttributeValue("bgColor2");
                TreeViewEntity treeEntity = new TreeViewEntity() { Data = newMenu };
                treeEntity.DataSon = GetMenus(xElement);
                treeEntity.IsChecked = false;
                treeEntity.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(treeEntity_PropertyChanged);
                list.Add(treeEntity);

            }
            return list;
        }

        /// <summary>
        /// 树中节点点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void treeEntity_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            TreeViewEntity TreeItem = sender as TreeViewEntity;
            if (TreeItem.DataSon.Count > 0)
            {

                foreach (TreeViewEntity temp in TreeItem.DataSon)
                {
                    //if (!temp.IsChecked)
                    temp.IsChecked = TreeItem.IsChecked;
                }

            }
        }

        /// <summary>
        /// 选中项转字符串
        /// </summary>
        string LevelTree()
        {
            string str = "";
            foreach (TreeViewEntity temp in Nodes)
            {
                if (temp.IsChecked)
                    str += (temp.Data as Menu).Id + ",";
                foreach (TreeViewEntity tempson in temp.DataSon)
                {
                    if (tempson.IsChecked)
                    {
                        if (!temp.IsChecked)
                        {
                            str.Replace((temp.Data as Menu).Id + ",", "");
                            str += (temp.Data as Menu).Id + ",";
                        }
                        str += (tempson.Data as Menu).Id + ",";
                    }

                }
            }
            return str;
        }
        /// <summary>
        /// 查询用户组
        /// </summary>
        void QueryGroup()
        {
            try
            {
                var data = new operatorGroup().ExtGetAll();
                OpGroup = new ObservableCollection<operatorGroup>(data);
            }
            catch
            {
            }
        }

        /// <summary>
        /// 利用反射赋值
        /// </summary>
        /// <param name="source">源数据</param>
        /// <param name="target">目标数据，不能为Null</param>
        private void RefGetValue(@operator source, @operator target)
        {
            if (source != null)
            {
                target.CreateDate = source.CreateDate;
                target.Desc = source.Desc;
                target.GroupCode = source.GroupCode;
                target.MercAcc = source.MercAcc;
                target.mercacc1 = source.mercacc1;
                target.operatorGroup = source.operatorGroup;
                target.OperCode = source.OperCode;
                target.Opername = source.Opername;
                target.OperPIN = source.OperPIN;
                target.OperType = source.OperType;
                target.Used = source.Used;
                target.USERIP = source.USERIP;

            }

            //if (source != null)
            //{
                
            //    Type t = source.GetType();
            //    PropertyInfo[] pi = t.GetProperties();
            //    foreach (PropertyInfo p in pi)
            //    {
            //        if (!p.PropertyType.IsGenericType && p.Name != "EntityState" && p.Name != "EntityKey")
            //        {
            //            PropertyInfo pii = source.GetProperty(p.Name);
            //            pii.SetValue(target, p.GetValue(source, null), null);
            //        }
            //    }
            //}
        }

        /// <summary>
        /// 获取IP
        /// </summary>
        /// <returns></returns>
        public string GetLocalIP()
        {
            IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in arrIPAddresses)
            {
                if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
                {
                    return ip.ToString();
                }
            }


            return "127.0.0.1";
        }
        /// <summary>
        /// 查询角色信息
        /// </summary>
        void QueryOPFunc()
        {
            var data = new @operator().ExtGetAll(true);
            OP = new ObservableCollection<@operator>(data);
        }

        /// <summary>
        ///  提示成功
        /// </summary>
        /// <param name="str"></param>
        void ShowSucceedMessage(string str)
        {
            //WindowBase.ShowMessageBox("提示", str, MessageBoxImage.Information, MessageBoxButton.OK);
            ShowMsg(str);
        }

        /// <summary>
        /// 提示失败
        /// </summary>
        /// <param name="str"></param>
        void ShowFailMessage(string str)
        {
            //WindowBase.ShowMessageBox("提示", str, MessageBoxImage.Error, MessageBoxButton.OK);
            ShowMsg(str, false);
        }

        ///// <summary>
        ///// 跟踪实体
        ///// </summary>
        ///// <param name="entityObj"></param>
        //void AttachEntity(object entityObj)
        //{
        //    try
        //    {
        //        bool isAttach = false;
        //        foreach (EntityDescriptor ed in WcfOneCardEntity.Entities)
        //        {
        //            if (!ed.Entity.HasProperty("Id"))
        //            {
        //                continue;
        //            }
        //            if (ed.Entity.GetType() == entityObj.GetType() &&
        //                    ed.Entity.GetPropertyValue("Id").Equals(entityObj.GetPropertyValue("Id")))
        //            {
        //                WcfOneCardEntity.Detach(ed.Entity);
        //                WcfOneCardEntity.AttachTo(entityObj.GetType().Name, entityObj);
        //                isAttach = true;
        //            }
        //        }
        //        if (!isAttach)
        //        {
        //            WcfOneCardEntity.AttachTo(entityObj.GetType().Name, entityObj);
        //        }
        //        //if (WcfOneCardEntity.Entities.All(p => p.Entity != entityObj))
        //        //{
        //        //    WcfOneCardEntity.AttachTo(entityObj.GetType().Name, entityObj);
        //        //}
        //    }
        //    catch
        //    {

        //    }
        //}

        #endregion
        #region 按钮命令
        private DelegateCommand _addgroupcommand;
        /// <summary>
        /// 添加一条组信息
        /// </summary>
        public DelegateCommand AddGroupCommand
        {
            get
            {
                return _addgroupcommand ?? (_addgroupcommand = new DelegateCommand(
                    () =>
                    {
                        try
                        {
                            if (TempOpGroup.Flag != null)
                            {
                                operatorGroup tempgroup = new operatorGroup()
                                {
                                    Name = TempOpGroup.Name,
                                    OPERDESC = TempOpGroup.OPERDESC,
                                    OperLevel = LevelTree(),
                                    Flag = TempOpGroup.Flag,
                                    USERPID = "1"
                                };
                                tempgroup.ExtAdd(); 
                                QueryGroup();
                                ShowSucceedMessage("添加成功！");
                                LoadData();
                            }
                            else
                            {
                                ShowSucceedMessage("请选择角色类型！");
                            }

                        }
                        catch (Exception e)
                        {
                            ShowFailMessage("添加失败！\r\n错误信息：" + e.Message);

                        }
                    }
                    ));
            }
        }




        private DelegateCommand _updategroupcommand;
        /// <summary>
        /// 更新角色组
        /// </summary>
        public DelegateCommand UpdateGroupCommand
        {
            get
            {
                return _updategroupcommand ?? (_updategroupcommand = new DelegateCommand(
                    () =>
                    {
                        try
                        {
                            if (SelecetedOpGroup != null)
                            {
                                TempOpGroup.OperLevel = LevelTree();
                                SelecetedOpGroup = TempOpGroup.Clone();
                                SelecetedOpGroup.ExtUpdate(); 
                                ShowSucceedMessage("更新成功！");
                                LoadData();
                            }
                            else
                            {
                                ShowFailMessage("请选择要更新的项！");
                            }
                        }
                        catch (Exception e)
                        {
                            ShowFailMessage("更新失败！\r\n错误信息：" + e.Message);

                        }
                    }
                    ));
            }
        }

        private DelegateCommand _delGroupcommand;
        /// <summary>
        /// 删除一条角色组
        /// </summary>
        public DelegateCommand DelGroupCommand
        {
            get
            {
                return _delGroupcommand ?? (_delGroupcommand = new DelegateCommand(
                    () =>
                    {
                        try
                        {
                            if (SelecetedOpGroup != null)
                            {
                                //AttachEntity(SelecetedOpGroup);
                                SelecetedOpGroup = new operatorGroup().ExtGetSingle("it.Id == @Id", true,
                                                                                    new SearchParameter("id",
                                                                                                        SelecetedOpGroup
                                                                                                            .Id)); 

                                if (SelecetedOpGroup.@operator.Count > 0 &&
                                    MessageBox.Show("此操作会删除相关操作员，是否执行？", "删除确认", MessageBoxButton.YesNo) ==
                                    MessageBoxResult.No)
                                {
                                    return;
                                }
                                foreach (@operator o in SelecetedOpGroup.@operator)
                                {
                                    o.ExtDelete();
                                }
                                SelecetedOpGroup.ExtDelete();
                                QueryGroup();
                                ShowSucceedMessage("删除成功！");
                                LoadData();
                            }
                            else
                            {
                                ShowFailMessage("请选择要删除的项！");
                            }
                        }
                        catch (Exception e)
                        {
                            ShowFailMessage("删除失败！\r\n错误信息：" + e.Message);

                        }
                    }
                    ));
            }
        }

        private DelegateCommand _querycommand;
        /// <summary>
        /// 查询
        /// </summary>
        public DelegateCommand QueryCommand
        {
            get
            {
                return _querycommand ?? (_querycommand = new DelegateCommand(
                    Queryoperator
                    ));
            }
        }
        void Queryoperator()
        {
            try
            {
                var sb = new StringBuilder("1==1");
                var paramList = new List<SearchParameter>();
                if (!string.IsNullOrEmpty(QueryOP.OperCode))
                {
                    sb.Append(" && it.OperCode like (@OperCode)");
                    paramList.Add(new SearchParameter("OperCode",QueryOP.OperCode));
                }
                if (QueryOP.Used != -1)
                {
                    sb.Append(" && it.Used==@Used ");
                    paramList.Add(new SearchParameter("Used", QueryOP.Used));
                }
                if (!string.IsNullOrEmpty(QueryOP.Opername))
                {
                    sb.Append(" && it.Opername like (@Opername)");
                    paramList.Add(new SearchParameter("Opername", QueryOP.Opername));
                }
                if (QueryOP.GroupCode != -1)
                {
                    sb.Append(" && it.GroupCode==@GroupCode ");
                    paramList.Add(new SearchParameter("GroupCode", QueryOP.GroupCode));
                }
                if (SelectMercaccsPlus != -1)
                {
                    sb.Append(" && it.MercAcc==@MercAcc ");
                    paramList.Add(new SearchParameter("MercAcc", SelectMercaccsPlus));
                }
               
                var data = new @operator().ExtGetAll(true, sb.ToString(),paramList.ToArray());

                if (data.Count() == 0)
                {
                    if (OP != null)
                        OP.Clear();
                    ShowSucceedMessage("未能找到相应数据，请重新输入条件！");
                }
                else
                {
                    OP = new ObservableCollection<@operator>(data);
                }

            }
            catch (Exception e)
            {
                ShowFailMessage("查询失败！\r\n错误信息：" + e.Message);

            }
        }


        private DelegateCommand _isshowcommand;
        /// <summary>
        /// 是否显示角色组编辑
        /// </summary>
        public DelegateCommand IsShowCommand
        {
            get
            {
                return _isshowcommand ?? (_isshowcommand = new DelegateCommand(
                    () =>
                    {
                        IsShow = IsShow == Visibility.Hidden ? Visibility.Visible : Visibility.Hidden;
                    }
                    ));
            }
        }


        private DelegateCommand _addOpcommand;

        /// <summary>
        /// 添加用户
        /// </summary>
        public DelegateCommand AddOpCommand
        {
            get
            {
                return _addOpcommand ?? (_addOpcommand = new DelegateCommand(
                        () =>
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(TempOP.OperCode) && !string.IsNullOrEmpty(TempOP.Opername) &&
                                      TempOP.MercAcc != null && TempOP.GroupCode != null)
                                {
                                    var a = new @operator().ExtCount("it.OperCode == @OperCode ",new SearchParameter("OperCode",TempOP.OperCode));
                                    if (a == 0)
                                    {
                                        @operator tempop = new @operator();
                                        TempOP.Flag = IsCash ? "1" : "0";

                                        tempop.CreateDate = TempOP.CreateDate;
                                        tempop.Desc = TempOP.Desc;
                                        tempop.GroupCode = TempOP.GroupCode;
                                        tempop.MercAcc = TempOP.MercAcc;
                                        tempop.OperCode = TempOP.OperCode;
                                        tempop.Opername = TempOP.Opername;
                                        tempop.OperPIN = TempOP.OperPIN;
                                        tempop.OperType = TempOP.OperType;
                                        tempop.Used = TempOP.Used;
                                        tempop.USERIP = TempOP.USERIP;

                                        tempop.OperType = int.Parse(OpGroup.First(
                                            p => p.Id == TempOP.GroupCode).Flag);
                                        tempop.CreateDate = DateTime.Now;
                                        tempop.ExtAdd();
                                        ShowSucceedMessage("添加成功！");
                                        if(OP==null||OP.Count==0)
                                        {
                                            return;
                                        }
                                        Queryoperator();
                                    }
                                    else
                                    {
                                        ShowFailMessage("添加失败！\r\n错误信息：此账号已存在");
                                    }
                                }
                                else
                                {
                                    ShowFailMessage("信息不完整！");
                                }
                            }
                            catch (Exception e)
                            {
                                ShowFailMessage("添加失败！\r\n错误信息：" + e.Message);

                            }

                        }
                                                             ));
            }
        }


        private DelegateCommand _updateOpcommand;
        /// <summary>
        /// 更新用户
        /// </summary>
        public DelegateCommand UpdateOpCommand
        {
            get
            {
                return _updateOpcommand ?? (_updateOpcommand = new DelegateCommand(
                    () =>
                    {
                        try
                        {
                            if (SelecetedOp == null)
                            {
                                ShowFailMessage("请选择要更新的项！");
                                return;
                            }
                            if (SelecetedOp.OperCode != TempOP.OperCode)
                            {
                                ShowFailMessage("账号不可修改！");
                                return;
                            }

                            TempOP.Flag = IsCash ? "1" : "0";
                            TempOP.OperType = int.Parse(OpGroup.First(p => p.Id == SelecetedOp.GroupCode).Flag);
                            TempOP.ExtUpdate();
                            var a=OP.Where(p => p.OperCode == TempOP.OperCode);
                            foreach(@operator o in a)
                            {
                                o.Opername = TempOP.Opername;
                                o.OperPIN = TempOP.OperPIN;
                                o.OperType = TempOP.OperType;
                                o.CreateDate = TempOP.CreateDate;
                                o.Desc = TempOP.Desc;
                                o.Flag = TempOP.Flag;
                                o.GroupCode = TempOP.GroupCode;
                                o.MercAcc = TempOP.MercAcc;
                                o.TypeStr = TempOP.TypeStr;
                                o.Used = TempOP.Used;
                                o.USERIP = TempOP.USERIP;
                            }
                            ShowSucceedMessage("更新成功！");
                        }
                        catch (Exception e)
                        {
                            ShowFailMessage("更新失败！\r\n错误信息：" + e.Message);

                        }
                    }
                    ));
            }
        }
        private DelegateCommand _delOpcommand;
        /// <summary>
        /// 删除用户
        /// </summary>
        public DelegateCommand DelOpCommand
        {
            get
            {
                return _delOpcommand ?? (_delOpcommand = new DelegateCommand(
                    () =>
                    {
                        try
                        {
                            if (SelecetedOp != null)
                            {
                                @operator tempop = new @operator();
                                tempop.CreateDate = SelecetedOp.CreateDate;
                                tempop.Desc = SelecetedOp.Desc;
                                tempop.GroupCode = SelecetedOp.GroupCode;
                                tempop.MercAcc = SelecetedOp.MercAcc;
                                tempop.OperCode = SelecetedOp.OperCode;
                                tempop.Opername = SelecetedOp.Opername;
                                tempop.OperPIN = SelecetedOp.OperPIN;
                                tempop.OperType = SelecetedOp.OperType;
                                tempop.Used = SelecetedOp.Used;
                                tempop.USERIP = SelecetedOp.USERIP;

                                tempop.ExtDelete();
                                ShowSucceedMessage("删除成功！");
                                OP.Remove(SelecetedOp);
                            }
                            else
                            {
                                ShowFailMessage("请选择要删除的项！");
                            }

                        }
                        catch (Exception e)
                        {
                            ShowFailMessage("删除失败！\r\n错误信息：" + e.Message);

                        }
                    }
                    ));
            }
        }

        /// <summary>
        /// 返回按钮
        /// </summary>
        public DelegateCommand OkCommand
        {
            get { return MainViewModel.Instance.ReturnToStartCommand; }
        }
        #endregion


    }


    [ValueConversion(typeof(string), typeof(String))]
    public class UsedConverter : IValueConverter
    {
        /// <summary>
        /// 是否可用转换器
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = "";
            try
            {
                if (value.ToString() == "0")
                    return str = "停用";
                else
                    return str = "启用";
            }
            catch
            {
            }
            return str;
        }

        public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}


